package com.example.springboot.config.bootcustomize.messageconverter;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/18 11:52
 */
public class CzkMessageConverter implements HttpMessageConverter<UserEntity> {
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return aClass.isAssignableFrom(UserEntity.class);
    }

    /**
     * 服务器需要统计所有的messageConverter
     *
     * @return 要支持的类型集合
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/czk");
    }

    @Override
    public UserEntity read(Class<? extends UserEntity> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(UserEntity userEntity, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        // 拼接要写回的数据
        String data=userEntity.getName()+"&"+userEntity.getAge();
        httpOutputMessage.getBody().write(data.getBytes());
    }
}
